package com.hmdp.utils;

import ch.qos.logback.core.util.TimeUtil;
import com.hmdp.constants.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import static com.hmdp.constants.RedisConstants.LOCK_KEY;

@Service
public class LockUtils {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public <ID> boolean tryLock(String service, ID id, String value) {
        Boolean lock = stringRedisTemplate.opsForValue()
                .setIfAbsent(LOCK_KEY + service + ":" + id, value, 100, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(lock);
    }

    public <ID> void removeLock(String service, ID id) {
        stringRedisTemplate.delete(LOCK_KEY + service + ":" + id);
    }
}
